<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['order:binding:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['order:binding:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['order:binding:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['order:binding:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bindingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="绑定子账户" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-edit"
            @click="handleBinding(scope.row)"
          >绑定/修改
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="抽成比例" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-edit"
            @click="handleRatio(scope.row)"
          >修改比例
          </el-button>
        </template>
      </el-table-column>

      <!--      <el-table-column label="记录ID" align="center" prop="id" />-->
      <el-table-column label="管理员昵称" align="center" prop="adminNickName"/>
      <el-table-column label="工作室昵称" align="center" prop="userNickName"/>
      <el-table-column label="本家地址" align="center" prop="clientAddress"/>
      <el-table-column label="上家地址" align="center" prop="supplierAddress"/>
      <el-table-column label="绑定的子账户昵称" align="center" prop="suUserName"/>
      <el-table-column label="创建/修改时间" align="center" prop="recordTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.recordTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['order:binding:edit']"
          >修改地址
          </el-button>
          <el-button
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['order:binding:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>


    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工作室改价比例对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col>
            <el-form-item label="本家地址" prop="clientAddress">
              <el-input v-model="form.clientAddress" placeholder="请输入本家地址"/>
            </el-form-item>
            <el-row :gutter="20">
              <el-col :span="10">
                <el-form-item label="用户名" prop="clientUsername">
                  <el-input v-model="form.clientUsername" placeholder="请输入本家登录用户名"/>
                </el-form-item>
              </el-col>
              <el-col :span="14">
                <el-form-item label="密码" prop="clientPassword">
                  <el-input v-model="form.clientPassword" placeholder="请输入本家登录密码"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="上家地址" prop="supplierAddress">
              <el-input v-model="form.supplierAddress" placeholder="请输入上家地址"/>
            </el-form-item>
            <el-row :gutter="20">
              <el-col :span="10">
                <el-form-item label="用户名" prop="supplierUsername">
                  <el-input v-model="form.supplierUsername" placeholder="请输入上家登录用户名"/>
                </el-form-item>
              </el-col>
              <el-col :span="14">
                <el-form-item label="密码" prop="supplierPassword">
                  <el-input v-model="form.supplierPassword" placeholder="请输入上家登录密码"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col v-if="!isUpdate">
            <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange" max-height="300">
              <el-table-column type="selection" width="50" align="center"/>
              <!--              <el-table-column label="用户编号" align="center" key="userId" prop="userId" v-if="columns[0].visible" />-->
              <el-table-column label="用户名称" align="center" key="userName" prop="userName"
                               :show-overflow-tooltip="true"/>
              <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName"
                               :show-overflow-tooltip="true"/>
              <el-table-column label="部门" align="center" key="deptName" prop="dept.deptName"
                               :show-overflow-tooltip="true"/>
              <!--              <el-table-co  lumn label="手机号码" align="center" key="phonenumber" prop="phonenumber" v-if="columns[4].visible" width="120" />-->
            </el-table>
            <pagination
              v-show="userTotal>0"
              :total="userTotal"
              :page.sync="userQueryParams.pageNum"
              :limit.sync="userQueryParams.pageSize"
              @pagination="getUserList"
              layout="total, prev, pager, next "
            />
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="bindingOpen" append-to-body>
      <!--      显示一个占位表格-->
      <el-table v-loading="loading" :data="childUserList" @selection-change="handleSelectionChange" max-height="640">
        <el-table-column type="index" width="55" align="center"/>
        <!--      <el-table-column label="记录ID" align="center" prop="id" />-->
        <el-table-column label="子账户昵称" align="center" prop="suUserName"/>
        <el-table-column label="子账户编号" align="center" prop="suUid"/>
        <el-table-column label="子账户标志" align="center" prop="suLoginAcc"/>
        <el-table-column label="可选游戏" align="center" prop="suGames"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              v-if="!isBinded"
              type="primary"
              icon="el-icon-edit"
              @click="bindingChildUser(scope.row)"
              v-hasPermi="['order:binding:edit']"
            >
              绑定子账户
            </el-button>
            <el-button
              v-else
              type="success"
              icon="el-icon-check"
              disabled
            >
              已绑定
            </el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-dialog>

    <el-dialog :title="title" :visible.sync="ratioOpen" append-to-body>
      <el-divider content-position="center">扣款比例信息</el-divider>

      <template v-if="form.suUid">
        <div
          class="block"
          v-for="(game, index) in gameList"
          :key="index"
          style="margin-bottom: 20px"
        >
          <span class="demonstration">游戏名称：{{ game }}</span>
          <el-slider
            v-model="ratios[game]"
            :show-input="true"
          ></el-slider>
        </div>
      </template>

      <template v-else>
        <el-empty description="请先绑定子系统用户"/>
      </template>

      <!-- 底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="handleRatioConfirm">确 定</el-button>
      </span>
    </el-dialog>


  <!--    <div style="padding: 20px">-->
  <!--      <h2>测试鸡蛋铺登录接口</h2>-->
  <!--      <el-button type="primary" @click="testLogin">提交登录</el-button>-->
  <!--      <el-button type="primary" @click="getChildUserList">获取子用户列表</el-button>-->
  <!--      <el-card v-if="response" style="margin-top: 20px">-->
  <!--        <pre>{{ response }}</pre>-->
  <!--      </el-card>-->
  <!--    </div>-->

  </div>
</template>

<script>
import {
  listBinding,
  getBinding,
  delBinding,
  addBinding,
  updateBinding,
  testLogin,
  listChildUser
} from "@/api/order/binding"
import {listUser} from "@/api/system/user";

export default {
  name: "Binding",
  data() {
    return {
      gameList: [],       // 存储游戏名数组
      ratios: {},         // 存储每个游戏的比例
      ratio: 0,
      ratioOpen: false,
      isBinded: false,
      response: null,
      // 用户表格数据
      isUpdate: false,
      userList: null,
      childUserList: [],
      gameCategories: [
        {id: '1', name: '原神'},
        {id: '2', name: '鸣潮'},
        {id: '3', name: '三角洲行动'},
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedMhUserGamePrice: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // user总条数
      userTotal: 0,
      // 工作室改价比例表格数据
      bindingList: [],
      // 扣款比例表格数据
      mhUserGamePriceList: [],
      // 弹出层标题
      title: "",
      // 是否显示新增弹出层
      open: false,
      // 是否显示binding弹出层
      bindingOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // user查询参数
      userQueryParams: {
        pageNum: 1,
        pageSize: 4,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        adminId: [
          {required: true, message: "管理员ID不能为空", trigger: "blur"}
        ],
        userId: [
          {required: true, message: "部门员工ID不能为空", trigger: "blur"}
        ],
        clientAddress: [
          {required: true, message: "本家地址不能为空", trigger: "blur"}
        ],
        supplierAddress: [
          {required: true, message: "上家地址不能为空", trigger: "blur"}
        ],
        clientUsername: [
          {required: true, message: "本家登录用户名不能为空", trigger: "blur"}
        ],
        clientPassword: [
          {required: true, message: "本家登录密码不能为空", trigger: "blur"}
        ],
        supplierUsername: [
          {required: true, message: "上家登录用户名不能为空", trigger: "blur"}
        ],
        supplierPassword: [
          {required: true, message: "上家登录密码不能为空", trigger: "blur"}
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  watch: {
    'form.suGames': {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          this.gameList = newVal.split(',');
          // 初始化每个游戏的比例为 0（或已有值）
          this.gameList.forEach(game => {
            if (!(game in this.ratios)) {
              this.$set(this.ratios, game, 0);
            }
          });
        } else {
          this.gameList = [];
        }
      }
    }
  },
  methods: {
    testLogin() {
      testLogin().then(response => {
        this.response = response
      })
    },
    /** 修改游戏比例 */
    handleRatioConfirm() {
      console.log('各游戏比例如下：');
      const gamePriceList = Object.entries(this.ratios).map(([gameCategoryName, priceRatio]) => ({
        gameCategoryName,
        priceRatio
      }));
      gamePriceList.forEach(item => {
        console.log(`${item.gameCategoryName}: ${item.priceRatio}`);
      });
      this.form.mhUserGamePriceList = gamePriceList;
      console.log(this.form)
      updateBinding(this.form).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.getList();
        this.ratioOpen = false;
      })

    },
    /** 查询用户列表 */
    getUserList() {
      this.loading = true
      listUser(this.addDateRange(this.userQueryParams, this.dateRange)).then(response => {
          this.userList = response.rows
          this.userTotal = response.total
          this.loading = false
        }
      )
    },
    /** 查询工作室子用户列表 */
    getChildUserList() {
      listChildUser(this.queryParams).then(response => {
        this.childUserList = response.rows
        this.userTotal = response.total
        this.loading = false
      })
    },
    /** 查询工作室改价比例列表 */
    getList() {
      this.loading = true
      listBinding(this.queryParams).then(response => {
        this.bindingList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    bindingChildUser(row) {

      this.form.suUid = row.suUid
      this.form.suLoginAcc = row.suLoginAcc
      this.form.suUserName = row.suUserName
      this.form.suGames = row.suGames
      console.log(this.form)
      updateBinding(this.form).then(response => {
        this.$modal.msgSuccess("修改成功")
        this.isBinded = true
        this.getList()
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.bindingOpen = false
      this.ratioOpen = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        adminId: null,
        userId: null,
        clientAddress: null,
        supplierAddress: null,
        recordTime: null,
        clientUsername: null,
        clientPassword: null,
        supplierUsername: null,
        supplierPassword: null,
        userIds: null
      }
      this.mhUserGamePriceList = []
      this.resetForm("form")
      this.getUserList()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
      this.getUserList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this.form.userIds = this.ids
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.isUpdate = false
      this.open = true
      this.title = "添加用户上下家地址"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.isUpdate = true
      this.reset()
      const id = row.id || this.ids
      getBinding(id).then(response => {
        this.form = response.data
        this.mhUserGamePriceList = response.data.mhUserGamePriceList
        this.open = true
        this.title = "修改用户上下家地址"
      })
    },
    handleBinding(row) {
      this.reset()
      const id = row.id || this.ids
      getBinding(id).then(response => {
        this.form = response.data
        this.mhUserGamePriceList = response.data.mhUserGamePriceList
        this.getChildUserList()
        this.bindingOpen = true
        this.isBinded = false
        this.title = "为用户绑定工作室子账号"
      })
    },
    /** 修改下家比例对话框 */
    handleRatio(row) {
      getBinding(row.id).then(response => {
        this.form = response.data

        // 清空原数据
        this.gameList = [];
        this.ratios = {};

        // 优先使用已有比例列表
        const ratioList = response.data.mhUserGamePriceList;

        if (ratioList && ratioList.length > 0) {
          // 后端已设置过比例：从 mhUserGamePriceList 中提取
          ratioList.forEach(item => {
            const gameName = item.gameCategoryName;
            const ratio = item.priceRatio;
            this.gameList.push(gameName);
            this.$set(this.ratios, gameName, ratio);
          });
        } else {
          // 尚未设置比例：从 suGames 中解析
          const suGames = response.data.suGames;
          if (suGames) {
            this.gameList = suGames.split(',').map(game => game.trim());
            this.gameList.forEach(game => {
              this.$set(this.ratios, game, 0); // 默认设置为 0
            });
          }
        }
        this.ratioOpen = true
        this.title = "修改下家比例"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.mhUserGamePriceList = this.mhUserGamePriceList
          console.log('传出数据', this.form)
          if (this.form.id != null) {
            console.log('传出数据', this.form)
            updateBinding(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addBinding(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除工作室改价比例编号为"' + ids + '"的数据项？').then(function () {
        return delBinding(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    /** 扣款比例序号 */
    rowMhUserGamePriceIndex({row, rowIndex}) {
      row.index = rowIndex + 1
    },
    /** 扣款比例添加按钮操作 */
    handleAddMhUserGamePrice() {
      let obj = {}
      obj.gameCategoryId = ""
      obj.priceRatio = ""
      this.mhUserGamePriceList.push(obj)
    },
    /** 扣款比例删除按钮操作 */
    handleDeleteMhUserGamePrice() {
      if (this.checkedMhUserGamePrice.length === 0) {
        this.$modal.msgError("请先选择要删除的扣款比例数据")
      } else {
        const mhUserGamePriceList = this.mhUserGamePriceList
        const checkedMhUserGamePrice = this.checkedMhUserGamePrice
        this.mhUserGamePriceList = mhUserGamePriceList.filter(function (item) {
          return checkedMhUserGamePrice.indexOf(item.index) === -1
        })
      }
    },
    /** 复选框选中数据 */
    handleMhUserGamePriceSelectionChange(selection) {
      this.checkedMhUserGamePrice = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('order/binding/export', {
        ...this.queryParams
      }, `binding_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
